//
//  ANReleaseTableViewController.m
//  Ants
//
//  Created by ZHM on 16/5/20.
//  Copyright © 2016年 ZHM. All rights reserved.
//

#import "ANReleaseTableViewController.h"
#import "ANProfieleHeader.h"
#import "ANTableViewProfileCell.h"
#import "ANReleaseTitleCell.h"

#import "TZImageManager.h"
#import "TZImagePickerController.h"
#import "LxGridViewFlowLayout.h"
#import "UIView+Layout.h"
#import "TZTestCell.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <Photos/Photos.h>
#import "TZVideoPlayerController.h"
#import "HMAsset.h"
#import "ANBuyCollectionView.h"

#import "ANInputQuantity.h"
#import "ANInputPriceView.h"
#import "ANTextView.h"
#import "ANOptionsView.h"
#import "HMPickerDataModel.h"
#import "HMPickerView.h"
#import "ANServicesTableViewController.h"
#import <CoreLocation/CoreLocation.h>

#define MaxImagesCount 9 //图片最大张数


#define ANTextViewBackgroundColor [UIColor colorWithRed:254/255.0f green:254/255.0f blue:254/255.0f alpha:1.0f]

@interface ANReleaseTableViewController ()<TZImagePickerControllerDelegate,UICollectionViewDataSource,UICollectionViewDelegate,CLLocationManagerDelegate,UITextViewDelegate,UITextFieldDelegate,ANOptionsViewDelegate,ANInputPriceViewDelegate,ANInputQuantityDelegate,ANServicesTableViewControllerDelegate,UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,ANBuyCollectionViewDelegate>{
    NSMutableArray *_selectedPhotos;
    NSMutableArray *_selectedAssets;
    NSMutableArray *_imageCaches;
    NSInteger _imageCachesRemove;
    BOOL _isSelectOriginalPhoto;
    CGFloat _itemWH;
    CGFloat _margin;
    LxGridViewFlowLayout *_layout;
}
@property (nonatomic, assign) float titleCellHight;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) UIImagePickerController *imagePickerVc;
@property (nonatomic, strong) CLLocationManager *manager;
@property (nonatomic, weak) ANArrowItem *productInfo;
@property (nonatomic, weak) ANArrowItem *locationItem;
@property (nonatomic, weak) ANArrowItem *services;
@property (nonatomic, weak) ANArrowItem *quantity;
@property (nonatomic, weak) HMPickerView *pickerView;
@property (nonatomic, weak) ANInputPriceView *inputPriceView;
@property (nonatomic, weak) ANInputQuantity *inputQuantity;
@property (nonatomic, strong) NSArray *productCategorys;

//编辑过退出 要求确认
@property (nonatomic, assign) BOOL isEditing;

//商品名称-商品描述
@property (nonatomic, weak) ANReleaseTitleCell *releaseTitleCell;
//商品价格
@property (nonatomic, weak) ANPriceItem *productPrice;
//商品服务
@property (nonatomic, strong) NSArray *servicesStr;
//位置
@property (nonatomic, strong) CLLocation *location;
@property (nonatomic, strong) NSArray *address;
//选中类型
@property (nonatomic, assign) NSInteger selectCategoryIndex;

@property (assign, nonatomic)  BOOL showTakePhotoBtnSwitch;  ///< 在内部显示拍照按钮
@property (assign, nonatomic)  BOOL sortAscendingSwitch;     ///< 照片排列按修改时间升序
@property (assign, nonatomic)  BOOL allowPickingVideoSwitch; ///< 允许选择视频
@property (assign, nonatomic)  BOOL allowPickingImageSwitch; ///< 允许选择图片
@property (assign, nonatomic)  BOOL allowPickingOriginalPhotoSwitch; ///< 允许选择原图
@property (assign, nonatomic)  BOOL showSheetSwitch; ///< 显示一个sheet,把拍照按钮放在外面

@end

@implementation ANReleaseTableViewController


- (NSArray *)productCategorys {
    if (!_productCategorys) {
        //本地获取
        _productCategorys = [ANBDProductCategory MR_findAllSortedBy:@"title" ascending:YES inContext:sharedWebService.sharedContext];
        //网络更新
        [sharedWebService fetchProductCategoryCompletion:^(NSArray *productCategorys, NSError *error) {
            if (!error) {
                _productCategorys = productCategorys;
            }
        }];
    }
    return _productCategorys;
}
- (NSMutableArray *)ANBDProductCategoryToString:(NSArray *)arrayANDB {
    NSMutableArray *arrayM = [NSMutableArray array];
    [arrayANDB enumerateObjectsUsingBlock:^(ANBDProductCategory *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSString *categoryName = obj.title;
        [arrayM addObject:categoryName];
    }];
    return arrayM;
}
- (HMPickerView *)pickerView {
    if (!_pickerView) {
        _pickerView = [HMPickerView pickerViewWithPickerDatas:[self ANBDProductCategoryToString:self.productCategorys] selectIndex:_selectCategoryIndex];
        //返回数据
        _pickerView.locationMessage = ^(NSString *str,HMPickerIndexPath index){
            _selectCategoryIndex = index.row;
            self.productInfo.subTilte = str;
            [self.tableView reloadData];
            _isEditing = YES;
        };
    }
    return _pickerView;
}

- (CLLocationManager *)manager {
    if (!_manager) {
        _manager = [[CLLocationManager alloc] init];
        _manager.delegate = self;
        _manager.distanceFilter = 10;
        _manager.desiredAccuracy = kCLLocationAccuracyBest;
        if(iOS8Later) {
            [_manager requestAlwaysAuthorization];
        }
        if (iOS9Later) {
            _manager.allowsBackgroundLocationUpdates = YES;
        }
    }
    return _manager;
}

- (void)configCollectionView {
    _showTakePhotoBtnSwitch = YES;  ///< 在内部显示拍照按钮
    _sortAscendingSwitch = NO;     ///< 照片排列按修改时间升序
    _allowPickingVideoSwitch = YES; ///< 允许选择视频
    _allowPickingImageSwitch = YES; ///< 允许选择图片
    _allowPickingOriginalPhotoSwitch = YES; ///< 允许选择原图
    _showSheetSwitch= NO; ///< 显示一个sheet,把拍照按钮放在外面
    
    _layout = [[LxGridViewFlowLayout alloc] init];
    _margin = 4;
    if (!_selectedPhotos) _selectedPhotos = [NSMutableArray array];
    if (!_selectedAssets) _selectedAssets = [NSMutableArray array];

    _itemWH = (self.view.tz_width - 2 * _margin - 4) / 3 - _margin;
    _layout.itemSize = CGSizeMake(_itemWH, _itemWH);
    _layout.minimumInteritemSpacing = _margin;
    _layout.minimumLineSpacing = _margin;
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(_margin, 140, self.view.tz_width - 2 * _margin, 123) collectionViewLayout:_layout];
    _collectionView.backgroundColor = ANTextViewBackgroundColor;
    _collectionView.alwaysBounceVertical = NO;//禁止滚动
    _collectionView.contentInset = UIEdgeInsetsMake(4, 0, 0, 2);
    _collectionView.scrollIndicatorInsets = UIEdgeInsetsMake(0, 0, 0, -2);
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    [_collectionView registerClass:[TZTestCell class] forCellWithReuseIdentifier:@"TZTestCell"];
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUpNav];
    //添加第1组
    [self setUpGroup_1];
    //添加第2组
    [self setUpGroup_2];
    //[self setUpGroup_3];
    //图片选择器
    [self configCollectionView];
    //-1 默认 未选
    _selectCategoryIndex = -1;
}
- (void)reverseGeocodeLocation {
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    __weak typeof(self) weakSelf = self;
    [geocoder reverseGeocodeLocation:_location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        if (placemarks.count == 0 || error) {
            return;
        }
        CLPlacemark *placemark = placemarks.lastObject;
        weakSelf.locationItem.subTilte = [NSString stringWithFormat:@"%@-%@-%@",placemark.administrativeArea,placemark.locality,placemark.subLocality];
        weakSelf.address = @[placemark.administrativeArea,placemark.locality,placemark.subLocality];
        [weakSelf.tableView reloadData];
    }];
}

#pragma mark --定位代理方法
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    CLLocation *location = [locations lastObject];
    _location = location;
    [self reverseGeocodeLocation];
    [self.manager stopUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    NSLog(@"定位失败啦:%@",error);
}
- (void)setUpGroup_1 {
    __weak typeof(self) weakSelf = self;
    
    ANArrowItem *location = [ANArrowItem itemWithTilte:@"" image:[UIImage imageNamed:@"location"]];
    location.subTilte = @"定位";
    location.option = ^(ANProfileBaseItem *item){
        //开始定位
        [weakSelf.manager startUpdatingLocation];
    };
    _locationItem = location;
    ANGuoupItem *group = [[ANGuoupItem alloc] init];
    group.items = @[location];
    //先添加一个空组 占位置
    ANGuoupItem *groupEmpty = [[ANGuoupItem alloc] init];
    [self.guoups addObject:groupEmpty];
    [self.guoups addObject:group];
}
- (void)setUpGroup_2 {
    __weak typeof(self) weakSelf = self;
    ANPriceItem *productPrice = [ANPriceItem itemWithTilte:@"产品价格"];
    productPrice.price = @"0.00";
    productPrice.originPrice = @"0.00";
    productPrice.option = ^(ANProfileBaseItem *item){
        weakSelf.inputPriceView = [ANInputPriceView showInputPriceViewToViewController:weakSelf];
        weakSelf.inputPriceView.priceField.text = weakSelf.productPrice.price;
        weakSelf.inputPriceView.originalPriceField.text = weakSelf.productPrice.originPrice;
    };
    _productPrice = productPrice;
    
    ANArrowItem *quantity = [ANArrowItem itemWithTilte:@"产品数量"];
    quantity.subTilte = @"0";
    quantity.option = ^(ANProfileBaseItem *item){
        weakSelf.inputQuantity = [ANInputQuantity showInputQuantityAtViewController:weakSelf];
        weakSelf.inputQuantity.quantityField.text = weakSelf.quantity.subTilte;
    };
    _quantity = quantity;
    
    ANArrowItem *productInfo = [ANArrowItem itemWithTilte:@"产品类型"];
    productInfo.option = ^(ANProfileBaseItem *item){
        [weakSelf pickerView];
    };
    _productInfo = productInfo;
    
    ANArrowItem *services = [ANArrowItem itemWithTilte:@"产品服务"];
    services.destVcClass = [ANServicesTableViewController class];
    _services = services;
    ANGuoupItem *group = [[ANGuoupItem alloc] init];
    //    group.headedTitle = @"aaa";productComment
    //    group.footerTitle = @"bbb";
    group.items = @[productPrice,quantity,productInfo,services];
    [self.guoups addObject:group];
}
//废弃方法
- (void)setUpGroup_3 {
    __weak typeof(self) weakSelf = self;
    ANlableItem *title = [[ANlableItem alloc] init];
    title.text = [NSString stringWithFormat:@"立即%@",self.title];
    title.option = ^(ANProfileBaseItem *item){
        //显示选择视图
        [ANOptionsView optionsViewWithTitle:weakSelf.title delegate:weakSelf];
    };
    ANGuoupItem *group = [[ANGuoupItem alloc] init];
    group.items = @[title];
    [self.guoups addObject:group];
}

#pragma mark - 点击键盘返回键
- (BOOL)textFieldShouldReturn:(UITextField *)theTextField {
    if (theTextField == _inputPriceView.originalPriceField ||
        theTextField == _inputPriceView.priceField) {
        [_inputPriceView hiddenInputPriceView];
        [theTextField resignFirstResponder];
        _productPrice.price = _inputPriceView.priceField.text;
        _productPrice.originPrice = _inputPriceView.originalPriceField.text;
        [self.tableView reloadData];
    }
    if (theTextField == _inputQuantity.quantityField) {
        [_inputQuantity hiddenInputQuantity];
        [theTextField resignFirstResponder];
        _quantity.subTilte = _inputQuantity.quantityField.text;
        [self.tableView reloadData];
    }
    return YES;
}
#pragma mark - 输入框代理方法
- (void)inputPriceViewHiddenCoverView {
    _productPrice.price = _inputPriceView.priceField.text;
    _productPrice.originPrice = _inputPriceView.originalPriceField.text;
    [self.tableView reloadData];
}
- (void)hiddenInputQuantity:(ANInputQuantity *)inputQuantity {
    _quantity.subTilte = inputQuantity.quantityField.text;
    [self.tableView reloadData];
}
#pragma mark --TableView 数据源方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.guoups.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    }
    ANGuoupItem *guoupItem = self.guoups[section];
    return guoupItem.items.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        if (!_releaseTitleCell) {
            ANReleaseTitleCell *cell = [ANReleaseTitleCell cellWithTableView:tableView collectionView:self.collectionView];
            _titleCellHight = cell.cellHight;
            _releaseTitleCell = cell;
            if (_product) {
                //修改 --初始化数据
                [self initializeData];
            }else {
                //修改 --初始化数据
            }
            return cell;
        }else {
            return _releaseTitleCell;
        }
    }
    ANTableViewProfileCell *cell = [ANTableViewProfileCell cellWithTableView:tableView];
    ANGuoupItem *group = self.guoups[indexPath.section];
    ANProfileBaseItem *item = group.items[indexPath.row];
    cell.item = item;
    return cell;
}
#pragma mark -点击CELL调用
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    self.indexCellClick = indexPath;
    ANGuoupItem *group = self.guoups[indexPath.section];
    ANProfileBaseItem *item = group.items[indexPath.row];
    if (item.option) {
        item.option(item);
    }else if (item.destVcClass) {
        if ([item.destVcClass isSubclassOfClass:[ANServicesTableViewController class]]) {
            ANServicesTableViewController *vc = [[ANServicesTableViewController alloc]init];
            vc.delegate = self;
            vc.selectServices = _servicesStr;
            [self.navigationController pushViewController:vc animated:YES];
        }else {
            id vc = [[item.destVcClass alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return self.titleCellHight;
    }
    return 44;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section > 1) {
        return 30;
    }
    return 0.01;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.1;
}
- (void)setUpNav {
    //边界
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 44, 0);
    self.view.backgroundColor = [UIColor colorWithRed:239/255.0f green:239/255.0f blue:244/255.0f alpha:1];
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(leftItemCilck)];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    if (_isEdit) {
        //删除商品
        UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithTitle:@"删除" style:UIBarButtonItemStylePlain target:self action:@selector(rightItemCilck)];
        self.navigationItem.rightBarButtonItem = rightItem;
    }
    //显示商品工具条
    NSArray *titles = _isEdit ? @[@"修改"]: @[@"添加"];
    [ANBuyCollectionView buyCollectionViewWithViewController:self titles:titles animation:YES];
    
    //添加通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(editingProductComplete) name:@"editingProductComplete"  object:nil];
}
- (void)editingProductComplete {
    _isEditing = YES;
}
- (void)rightItemCilck {
    [self.view endEditing:YES];
    if (_isEdit) {
        //删除商品
        [ANOptionsView optionsViewWithTitle:@"删除" delegate:self];
    }
}
- (void)leftItemCilck {
    [self.view endEditing:YES];
    if (_isEditing) {
        [ANOptionsView optionsViewWithTitle:self.navigationItem.leftBarButtonItem.title delegate:self];
    } else {
        if (!_isEdit) [_product MR_deleteEntity];
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}
- (ANBDProduct *)product {
    if (!_product) {
        ANBDProduct *product = [ANBDProduct MR_createEntityInContext:sharedWebService.defaultContext];
        product.title = _releaseTitleCell.textTitle.text;
        product.intro = _releaseTitleCell.textView.text;
        product.price = [NSDecimalNumber decimalNumberWithString:_productPrice.price];
        product.originalPrice = [NSDecimalNumber decimalNumberWithString:_productPrice.originPrice];
        product.quantity = [NSNumber numberWithInteger: [_quantity.subTilte integerValue]];
        product.location = _location;
        product.address = _address;
        product.services = _servicesStr;
        _product = product;
    }
    return _product;
}
- (void)loadPhotos {
    ANLog(@"photos==%lu",_product.icons.count);
    UIImage *placeholderImage = [UIImage imageNamed:@"failure"];
    _imageCachesRemove = _product.icons.count;
     int i = 1000;
    _imageCaches = [NSMutableArray array];
    for (NSDictionary *imageDic in _product.icons) {
        HMAsset *asset = [[HMAsset alloc] init];
        asset.imageURL = imageDic[@"maxPic"];;
        asset.image = placeholderImage;
        asset.mediaType =  PHAssetMediaTypeImage;
        asset.localIdentifier = [NSString stringWithFormat:@"%@_%d",[HMAsset class],i];
        [_selectedAssets addObject:asset];
        [_selectedPhotos addObject:placeholderImage];
        
        UIImageView *imageView = [[UIImageView alloc] init];
        [imageView sd_setImageWithURL:asset.imageURL.toURL placeholderImage:placeholderImage options:SDWebImageRetryFailed progress:^(NSInteger receivedSize, NSInteger expectedSize) {
            
        } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            if (!error) {
                for (int i = 0;i < _selectedAssets.count;i++) {
                    id asset = _selectedAssets[i];
                    if ([asset isKindOfClass:[HMAsset class]]) {
                        HMAsset *hmAsset = (HMAsset *)asset;
                        if ([hmAsset.imageURL isEqualToString:[imageURL absoluteString]]) {
                            _imageCachesRemove--;
                            [_selectedPhotos replaceObjectAtIndex:i withObject:image];
                            hmAsset.image = image;
                            [_collectionView reloadData];
                            if (_imageCachesRemove == 0) {
                                //全部下载完 清空内存
                                [_imageCaches removeAllObjects];
                            }
                        }
                    }
                }
            } else {
                //下载图片失败
            }
        }];
        [_imageCaches addObject:imageView];
        i++;
    }
}
- (void)initializeData {
    if (self.product.mlObjectId) {
        _releaseTitleCell.textTitle.text = _product.title;
        _releaseTitleCell.textView.text = _product.intro;
        _releaseTitleCell.textView.hiddenPlaceHolder = YES;
        _productPrice.price = [_product.price stringValue];
        _productPrice.originPrice = [_product.originalPrice stringValue];
        //网络获取商品实时数量
        [sharedWebService fetchProductQuantity:_product completion:^(NSInteger quantity, NSError *error) {
            if (!error) {
                _quantity.subTilte = [NSString stringWithFormat:@"%ld",quantity];
                [self.tableView reloadData];
            }
        }];
        ANLog(@"quantity==%@",_product.quantity);
        _location = _product.location;
        self.locationItem.subTilte = [NSString stringWithFormat:@"%@-%@-%@",_product.address[0],_product.address[1],_product.address[2]];
        //[self reverseGeocodeLocation];
        
        //加载图片
        [self loadPhotos];
        //更新高度
        _layout.itemCount = _selectedPhotos.count;
        [self upCollectionViewHeight];
        [_collectionView reloadData];
        
        //获得类类索引
        int i = 0;
        for (ANBDProductCategory *OneCategory in self.productCategorys) {
            if ([OneCategory.title isEqualToString: _product.category.title]) {
                _selectCategoryIndex = i;
                break;
            }
            i++;
        }
        _services.subTilte = [NSString stringWithFormat:@"%lu个服务",_product.services.count];
        _servicesStr = _product.services;
        self.productInfo.subTilte = [_productCategorys[_selectCategoryIndex] title];
        [self.tableView reloadData];
    }
}
- (void)servicesSelectFinish:(NSArray *)selectServices {
    ANGuoupItem *group = selectServices[0];
    NSMutableArray *arrayM = [NSMutableArray array];
    for (ANCheakItem *item in group.items) {
        if (item.cheak) {
            [arrayM addObject:item.tilte];
        }
    }
    _servicesStr = arrayM;
    _services.subTilte = [NSString stringWithFormat:@"%ld个服务",(unsigned long)arrayM.count];
    [self.tableView reloadData];
}

- (void)saveContext {
    [sharedWebService.defaultContext MR_saveToPersistentStoreWithCompletion:^(BOOL success, NSError *error) {
        if(success){
            NSLog(@"you successfully saved your context");
        }else if(error){
            NSLog(@"error saving context:%@",error.description);
        }
    }];
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self saveContext];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
#pragma mark -- 保存修改商品
- (void)saveModifyProduct {
    NSMutableArray *prepareMaxDelete = [NSMutableArray array];
    NSMutableArray *prepareMinDelete = [NSMutableArray array];
    ANLog(@"%@",_product.icons);
    for (NSDictionary *dic in _product.icons) {
        [prepareMaxDelete addObject:dic[@"maxPic"]];
        [prepareMinDelete addObject:dic[@"minPic"]];
    }
    NSMutableArray *fileUrls = [NSMutableArray array];
    NSMutableArray *prepareUpload = [NSMutableArray array];
    for (int i = 0; i < _selectedAssets.count; i++) {
        if ([_selectedAssets[i] isKindOfClass:[HMAsset class]]) {
            HMAsset *hmAsset = (HMAsset *)_selectedAssets[i];
            ANLog(@"%@----%d",hmAsset.imageURL,i);
            NSInteger index = [prepareMaxDelete indexOfObject:hmAsset.imageURL];
            [fileUrls addObject:@{@"maxPic":hmAsset.imageURL,@"minPic":prepareMinDelete[index]}];
            [prepareMaxDelete removeObject:hmAsset.imageURL];
            [prepareMinDelete removeObjectAtIndex:index];
        }else {
            [fileUrls addObject:@{@"maxPic":@"0",@"minPic":@"0"}];
            [prepareUpload addObject:_selectedPhotos[i]];
        }
    }
    //删除max图片
    [sharedWebService removeFilesWithArray:prepareMaxDelete completion:^(NSArray *filePaths, BOOL succeeded, NSError *error) {
        if (!error) {
            ANLog(@"删除文件成功:%ld",(unsigned long)filePaths.count);
        } else {
            ANLog(@"删除文件失败:%@",error);
        }
    }];
    //删除MIN图片
    [sharedWebService removeFilesWithArray:prepareMinDelete completion:^(NSArray *filePaths, BOOL succeeded, NSError *error) {
        if (!error) {
            ANLog(@"删除小图片成功:%ld",(unsigned long)filePaths.count);
        } else {
            ANLog(@"删除小图片失败:%@",error);
        }
    }];
    if (prepareUpload.count) {
        //上传图片
        __weak typeof(self) weakSelf = self;
        [sharedWebService uploadPhotos:prepareUpload completion:^(NSArray *filePaths, BOOL succeeded, NSError *error) {
            if (!error && succeeded) {
                for (NSDictionary *dic in filePaths) {
                     for (int i = 0; i < fileUrls.count; i++) {
                         NSDictionary *fileDic = fileUrls[i];
                        if ([fileDic[@"maxPic"] isEqualToString:@"0"]) {
                            fileUrls[i] = dic;
                            break;
                        }
                    }
                }
                [weakSelf upProductDataWithFileUrls:fileUrls];
            }
        }];
    } else {
        [self upProductDataWithFileUrls:fileUrls];
    }
}
- (void)upProductDataWithFileUrls:(NSArray *)fileUrls {
    NSString *objectId = _product.mlObjectId;
    ANBDProductCategory *beforeCategory = _product.category;
    _product = nil;
    self.product.icons = fileUrls;
    _product.mlObjectId = objectId;
    //修改Wweb数据
    ANBDProductCategory *productCategory = _productCategorys[_selectCategoryIndex];
    __weak typeof(self) weakSelf = self;
    [sharedWebService updateProduct:_product Category:productCategory beforeCategory:beforeCategory completion:^(BOOL succeeded, NSError *error) {
        if (succeeded) {
            //发送通知 刷新
            [[NSNotificationCenter defaultCenter] postNotificationName:@"ReleaseNewProductComplete" object:nil];
            [weakSelf dismissViewControllerAnimated:YES completion:nil];
        }
    }];
}
#pragma mark - 发布新商品
- (void)releaseNewProduct {
    if (_selectCategoryIndex == -1) {
        [SVProgressHUD showErrorWithStatus:@"分类未设置!"];
        return;
    }
    //上传图片
    [sharedWebService uploadPhotos:_selectedPhotos completion:^(NSArray *filePaths, BOOL succeeded, NSError *error) {
        if (!error && succeeded) {
            _product = nil;
            self.product.icons = filePaths;
            //上传数据
            ANBDProductCategory *productCategory = _productCategorys[_selectCategoryIndex];
            [sharedWebService releaseNewProduct: _product Category:productCategory completion:^(BOOL succeeded, NSError *error) {
                if (succeeded && !error) {
                    //[_product MR_deleteEntity];
                    //[self dismissViewControllerAnimated:YES completion:nil];
                    //发送通知 刷新
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"ReleaseNewProductComplete" object:nil];
                }
            }];
        }
    }];
}
#pragma mark --确认退出控制器
- (void)optionsView:(ANOptionsView *)optionsView didClickBtn:(NSInteger)index {
    if (index == 1) {
        if ([optionsView.showString isEqualToString:self.navigationItem.rightBarButtonItem.title]) {
            if (_isEdit) {
                //编辑 右键
                [[NSNotificationCenter defaultCenter] postNotificationName:@"RemoveProductComplete" object:nil];
                [self dismissViewControllerAnimated:YES completion:nil];
            } else {
                //添加 右键
            }
        }
        if ([optionsView.showString isEqualToString:self.navigationItem.leftBarButtonItem.title]){
            if (!_isEdit) [_product MR_deleteEntity];
            [self dismissViewControllerAnimated:YES completion:nil];
        }
    }
}
#pragma mark -- 确认
- (void)clickConfirmBuyCollectionView:(ANBuyCollectionView *)buyCollectionView {
    if (_isEdit) {
        ANLog(@"确认%@",self.title);
        [self saveModifyProduct];
    } else {
        ANLog(@"确认%@",self.title);
        [self releaseNewProduct];
    }
}

#pragma mark-开始拖拽 代理方法
- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView {
    //隐藏键盘
    [self.view endEditing:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark UICollectionView

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _selectedPhotos.count + 1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    TZTestCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"TZTestCell" forIndexPath:indexPath];
    cell.videoImageView.hidden = YES;
    if (indexPath.row == _selectedPhotos.count) {
        cell.imageView.image = [UIImage imageNamed:@"AlbumAddBtn.png"];
        cell.deleteBtn.hidden = YES;
    } else {
        cell.imageView.image = _selectedPhotos[indexPath.row];
        cell.asset = _selectedAssets[indexPath.row];
        cell.deleteBtn.hidden = NO;
    }
    cell.deleteBtn.tag = indexPath.row;
    [cell.deleteBtn addTarget:self action:@selector(deleteBtnClik:) forControlEvents:UIControlEventTouchUpInside];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == _selectedPhotos.count) {
        BOOL showSheet = self.showSheetSwitch;
        if (showSheet) {
            UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"去相册选择", nil];
            [sheet showInView:self.view];
        } else {
            [self pushImagePickerController];
        }
    } else { // preview photos or video / 预览照片或者视频
        id asset = _selectedAssets[indexPath.row];
        BOOL isVideo = NO;
        if ([asset isKindOfClass:[PHAsset class]]) {
            PHAsset *phAsset = asset;
            isVideo = phAsset.mediaType == PHAssetMediaTypeVideo;
        } else if ([asset isKindOfClass:[ALAsset class]]) {
            ALAsset *alAsset = asset;
            isVideo = [[alAsset valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypeVideo];
        } else if ([asset isKindOfClass:[HMAsset class]]) {
            HMAsset *hmAsset = asset;
            isVideo = hmAsset.mediaType == PHAssetMediaTypeVideo;
        }
        if (isVideo) { // perview video / 预览视频
            TZVideoPlayerController *vc = [[TZVideoPlayerController alloc] init];
            TZAssetModel *model = [TZAssetModel modelWithAsset:asset type:TZAssetModelMediaTypeVideo timeLength:@""];
            vc.model = model;
            [self presentViewController:vc animated:YES completion:nil];
        } else { // preview photos / 预览照片
            TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithSelectedAssets:_selectedAssets selectedPhotos:_selectedPhotos index:indexPath.row];
            imagePickerVc.allowPickingOriginalPhoto = self.allowPickingOriginalPhotoSwitch;
            imagePickerVc.isSelectOriginalPhoto = _isSelectOriginalPhoto;
            __weak typeof(self) weakSelf = self;
            [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
                _selectedPhotos = [NSMutableArray arrayWithArray:photos];
                _selectedAssets = [NSMutableArray arrayWithArray:assets];
                _isSelectOriginalPhoto = isSelectOriginalPhoto;
                _layout.itemCount = _selectedPhotos.count;
                [_collectionView reloadData];
                //更新高度
                [weakSelf upCollectionViewHeight];
            }];
            [self presentViewController:imagePickerVc animated:YES completion:nil];
        }
    }
}

- (void)pushImagePickerController {
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:MaxImagesCount  delegate:self];
    
#pragma mark - 四类个性化设置，这些参数都可以不传，此时会走默认设置
    imagePickerVc.isSelectOriginalPhoto = _isSelectOriginalPhoto;
    
    // 1.如果你需要将拍照按钮放在外面，不要传这个参数
    imagePickerVc.selectedAssets = _selectedAssets; // optional, 可选的
    imagePickerVc.allowTakePicture = self.showTakePhotoBtnSwitch; // 在内部显示拍照按钮
    
    // 2. Set the appearance
    // 2. 在这里设置imagePickerVc的外观
    // imagePickerVc.navigationBar.barTintColor = [UIColor greenColor];
    // imagePickerVc.oKButtonTitleColorDisabled = [UIColor lightGrayColor];
    // imagePickerVc.oKButtonTitleColorNormal = [UIColor greenColor];
    
    // 3. Set allow picking video & photo & originalPhoto or not
    // 3. 设置是否可以选择视频/图片/原图
    imagePickerVc.allowPickingVideo = self.allowPickingVideoSwitch;
    imagePickerVc.allowPickingImage = self.allowPickingImageSwitch;
    imagePickerVc.allowPickingOriginalPhoto = self.allowPickingOriginalPhotoSwitch;
    
    // 4. 照片排列按修改时间升序
    imagePickerVc.sortAscendingByModificationDate = _sortAscendingSwitch;
    __weak typeof(self) weakSelf = self;
    // You can get the photos by block, the same as by delegate.
    // 你可以通过block或者代理，来得到用户选择的照片.
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        //更新高度
        [weakSelf upCollectionViewHeight];
    }];
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}
//拖拽移动调用
- (void)collectionView:(UICollectionView *)collectionView itemAtIndexPath:(NSIndexPath *)sourceIndexPath didMoveToIndexPath:(NSIndexPath *)destinationIndexPath {
    if (sourceIndexPath.item >= _selectedPhotos.count || destinationIndexPath.item >= _selectedPhotos.count) return;
    UIImage *image = _selectedPhotos[sourceIndexPath.item];
    if (image) {
        [_selectedPhotos exchangeObjectAtIndex:sourceIndexPath.item withObjectAtIndex:destinationIndexPath.item];
        [_selectedAssets exchangeObjectAtIndex:sourceIndexPath.item withObjectAtIndex:destinationIndexPath.item];
        [_collectionView reloadData];
    }
}

#pragma mark Click Event

- (void)deleteBtnClik:(UIButton *)sender {
    _isEditing = YES;
    [_selectedPhotos removeObjectAtIndex:sender.tag];
    [_selectedAssets removeObjectAtIndex:sender.tag];
    _layout.itemCount = _selectedPhotos.count;
    __weak typeof(self) weakSelf = self;

    [_collectionView performBatchUpdates:^{
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:sender.tag inSection:0];
        [_collectionView deleteItemsAtIndexPaths:@[indexPath]];
    } completion:^(BOOL finished) {
        if (finished) {
            [weakSelf upCollectionViewHeight];
            [_collectionView reloadData];
        }
    }];
}

//更新View高度
- (void)upCollectionViewHeight {
    NSInteger numCount = _selectedPhotos.count + 1;
    CGRect rect = _collectionView.frame;
    rect.size.height = numCount / 3 * 123;
    if (numCount % 3 && _selectedPhotos.count < MaxImagesCount) {
        rect.size.height += 123;
    }
    _collectionView.frame = rect;
    rect.origin.y = CGRectGetMaxY(rect);
    rect.size.height = 44;
    _titleCellHight = CGRectGetMaxY(_collectionView.frame);
    //刷新表格
    [self.tableView reloadData];
}


#pragma mark TZImagePickerControllerDelegate

/// User click cancel button
/// 用户点击了取消
// - (void)imagePickerControllerDidCancel:(TZImagePickerController *)picker {
// NSLog(@"cancel");
// }

// The picker should dismiss itself; when it dismissed these handle will be called.
// If isOriginalPhoto is YES, user picked the original photo.
// You can get original photo with asset, by the method [[TZImageManager manager] getOriginalPhotoWithAsset:completion:].
// The UIImage Object in photos default width is 828px, you can set it by photoWidth property.
// 这个照片选择器会自己dismiss，当选择器dismiss的时候，会执行下面的代理方法
// 如果isSelectOriginalPhoto为YES，表明用户选择了原图
// 你可以通过一个asset获得原图，通过这个方法：[[TZImageManager manager] getOriginalPhotoWithAsset:completion:]
// photos数组里的UIImage对象，默认是828像素宽，你可以通过设置photoWidth属性的值来改变它
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto {
    _selectedPhotos = [NSMutableArray arrayWithArray:photos];
    _selectedAssets = [NSMutableArray arrayWithArray:assets];
    _isSelectOriginalPhoto = isSelectOriginalPhoto;
    _layout.itemCount = _selectedPhotos.count;
    [_collectionView reloadData];
    _isEditing = YES;
}

// If user picking a video, this callback will be called.
// If system version > iOS8,asset is kind of PHAsset class, else is ALAsset class.
// 如果用户选择了一个视频，下面的handle会被执行
// 如果系统版本大于iOS8，asset是PHAsset类的对象，否则是ALAsset类的对象
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingVideo:(UIImage *)coverImage sourceAssets:(id)asset {
    _selectedPhotos = [NSMutableArray arrayWithArray:@[coverImage]];
    _selectedAssets = [NSMutableArray arrayWithArray:@[asset]];
    _layout.itemCount = _selectedPhotos.count;
    // open this code to send video / 打开这段代码发送视频
    // [[TZImageManager manager] getVideoOutputPathWithAsset:asset completion:^(NSString *outputPath) {
    // NSLog(@"视频导出到本地完成,沙盒路径为:%@",outputPath);
    // Export completed, send video here, send by outputPath or NSData
    // 导出完成，在这里写上传代码，通过路径或者通过NSData上传
    
    // }];
    [_collectionView reloadData];
    // _collectionView.contentSize = CGSizeMake(0, ((_selectedPhotos.count + 2) / 3 ) * (_margin + _itemWH));
}

- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    if ([type isEqualToString:@"public.image"]) {
        TZImagePickerController *tzImagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:9 delegate:self];
        tzImagePickerVc.sortAscendingByModificationDate = self.sortAscendingSwitch;
        [tzImagePickerVc showProgressHUD];
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        // save photo and get asset / 保存图片，获取到asset
        [[TZImageManager manager] savePhotoWithImage:image completion:^{
            [[TZImageManager manager] getCameraRollAlbum:NO allowPickingImage:YES completion:^(TZAlbumModel *model) {
                [[TZImageManager manager] getAssetsFromFetchResult:model.result allowPickingVideo:NO allowPickingImage:YES completion:^(NSArray<TZAssetModel *> *models) {
                    [tzImagePickerVc hideProgressHUD];
                    TZAssetModel *assetModel = [models firstObject];
                    if (tzImagePickerVc.sortAscendingByModificationDate) {
                        assetModel = [models lastObject];
                    }
                    [_selectedAssets addObject:assetModel.asset];
                    [_selectedPhotos addObject:image];
                    [_collectionView reloadData];
                }];
            }];
        }];
    }
}
#pragma mark - UIActionSheetDelegate

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) { // take photo / 去拍照
        [self takePhoto];
    } else if (buttonIndex == 1) {
        [self pushImagePickerController];
    }
}
#pragma mark - UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) { // 去设置界面，开启相机访问权限
        if (iOS8Later) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
        } else {
            // [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=Privacy&path=Photos"]];
        }
    }
}
- (void)takePhoto {
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if ((authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) && iOS8Later) {
        // 无权限 做一个友好的提示
        UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"无法使用相机" message:@"请在iPhone的""设置-隐私-相机""中允许访问相机" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"设置", nil];
        [alert show];
    } else { // 调用相机
        UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
        if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
            self.imagePickerVc.sourceType = sourceType;
            if(iOS8Later) {
                _imagePickerVc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
            }
            [self presentViewController:_imagePickerVc animated:YES completion:nil];
        } else {
            NSLog(@"模拟器中无法打开照相机,请在真机中使用");
        }
    }
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (UIImagePickerController *)imagePickerVc {
    if (_imagePickerVc == nil) {
        _imagePickerVc = [[UIImagePickerController alloc] init];
        _imagePickerVc.delegate = self;
        // set appearance / 改变相册选择页的导航栏外观
        _imagePickerVc.navigationBar.barTintColor = self.navigationController.navigationBar.barTintColor;
        _imagePickerVc.navigationBar.tintColor = self.navigationController.navigationBar.tintColor;
        UIBarButtonItem *tzBarItem, *BarItem;
        if (iOS9Later) {
            tzBarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[TZImagePickerController class]]];
            BarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UIImagePickerController class]]];
        } else {
            tzBarItem = [UIBarButtonItem appearanceWhenContainedIn:[TZImagePickerController class], nil];
            BarItem = [UIBarButtonItem appearanceWhenContainedIn:[UIImagePickerController class], nil];
        }
        NSDictionary *titleTextAttributes = [tzBarItem titleTextAttributesForState:UIControlStateNormal];
        [BarItem setTitleTextAttributes:titleTextAttributes forState:UIControlStateNormal];
    }
    return _imagePickerVc;
}
- (void)dealloc {
    ANLog(@"管理界面消失:%s",__func__);
}


@end
